using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine; // 需要安装Newtonsoft.Json包
public sealed class HttpClientService
    {
        #region Singleton Implementation
        private static readonly Lazy<HttpClientService> _instance =
            new(() => new HttpClientService());

        public static HttpClientService Instance => _instance.Value;

        private readonly HttpClient _client;

        private HttpClientService()
        {
            _client = new HttpClient
            {
                // 默认配置
                Timeout = TimeSpan.FromSeconds(30)
            };
            DefaultHeaders = new Dictionary<string, string>
            {
                {"Accept", "application/json"},
                {"User-Agent", "UnityHttpClient/1.0"}
            };
        }
        #endregion

        #region Configuration
        public Dictionary<string, string> DefaultHeaders { get; }

        // 添加默认请求头的方法
        public HttpClientService AddDefaultHeader(string key, string value)
        {
            DefaultHeaders[key] = value;
            return this;
        }
        
        public HttpClientService SetBaseUrl(string baseUrl)
        {
            _client.BaseAddress = new Uri(baseUrl);
            return this;
        }
        
        // 添加获取BaseUrl的方法
        public string GetBaseUrl()
        {
            return _client.BaseAddress?.ToString();
        }
        
        public HttpClientService SetTimeout(TimeSpan timeout)
        {
            _client.Timeout = timeout;
            return this;
        }
        #endregion

        #region Request Factory
        public Request Get(string path) => new(HttpMethod.Get, path);
        public Request Post(string path) => new(HttpMethod.Post, path);

        public class Request
        {
            private readonly HttpRequestMessage _request;
            private Dictionary<string, string> _queryParams;
            private object _bodyData;
            private string _customBody;
            private string _contentType = "application/json";
            private int _maxRetries = 3; // 最大重试次数
            private int _retryDelayMs = 1000; // 重试延迟（毫秒）

            internal Request(HttpMethod method, string path)
            {
                // 合并基础 URL 和相对路径，构建绝对路径
                var absolutePath = new Uri(new Uri(HttpClientService.Instance.GetBaseUrl()), path).ToString();
                _request = new HttpRequestMessage(method, absolutePath);
            }

            public Request AddHeader(string key, string value)
            {
                _request.Headers.TryAddWithoutValidation(key, value);
                return this;
            }

            public Request AddQueryParam(string key, string value)
            {
                _queryParams ??= new Dictionary<string, string>();
                _queryParams[key] = value;
                return this;
            }

            public Request SetBody<T>(T data)
            {
                _bodyData = data;
                return this;
            }

            public Request SetBody(string rawBody, string contentType = "text/plain")
            {
                _customBody = rawBody;
                _contentType = contentType;
                return this;
            }

            // 设置重试参数
            public Request SetRetry(int maxRetries, int retryDelayMs)
            {
                _maxRetries = maxRetries;
                _retryDelayMs = retryDelayMs;
                return this;
            }

            public async Task<Response> SendAsync()
            {
                int retryCount = 0;
                Exception lastException = null;

                while (retryCount <= _maxRetries)
                {
                    try
                    {
                        if (retryCount > 0)
                        {
                            Debug.Log($"重试请求 ({retryCount}/{_maxRetries}): {_request.Method} {_request.RequestUri}");
                            await Task.Delay(_retryDelayMs * retryCount); // 递增延迟
                        }

                        BuildRequest();
                        ApplyDefaultHeaders();
                        
                        // 添加详细的请求日志
                        Debug.Log($"发送HTTP请求: {_request.Method} {_request.RequestUri}");
                        Debug.Log($"请求头: {string.Join(", ", _request.Headers)}");
                        
                        var response = await Instance._client.SendAsync(_request);
                        
                        // 添加响应日志
                        Debug.Log($"收到响应: {(int)response.StatusCode} {response.StatusCode}");
                        var result = await ProcessResponse(response);

                        // 如果是服务器错误(5xx)或网络错误，则重试
                        if (!result.IsSuccess && 
                            (result.StatusCode >= HttpStatusCode.InternalServerError || 
                             result.StatusCode == HttpStatusCode.RequestTimeout))
                        {
                            lastException = new Exception($"HTTP错误: {result.StatusCode}");
                            retryCount++;
                            continue;
                        }

                        return result;
                    }
                    catch (HttpRequestException ex)
                    {
                        lastException = ex;
                        Debug.LogWarning($"请求异常 (尝试 {retryCount + 1}/{_maxRetries + 1}): {ex.Message}");
                        retryCount++;
                    }
                    catch (TaskCanceledException ex)
                    {
                        lastException = ex;
                        Debug.LogWarning($"请求超时 (尝试 {retryCount + 1}/{_maxRetries + 1}): {ex.Message}");
                        retryCount++;
                    }
                    catch (Exception ex)
                    {
                        lastException = ex;
                        Debug.LogError($"未预期的异常: {ex.Message}");
                        return new Response { IsSuccess = false, ErrorMessage = ex.Message };
                    }
                }

                return new Response 
                { 
                    IsSuccess = false, 
                    ErrorMessage = $"请求失败，已重试{_maxRetries}次。最后错误: {lastException?.Message}" 
                };
            }

            private void BuildRequest()
            {
                // 处理查询参数
                if (_queryParams != null)
                {
                    var baseUri = _request.RequestUri;
                    if (baseUri == null)
                    {
                        throw new InvalidOperationException("RequestUri is null.");
                    }
                    var query = new StringBuilder();
                    foreach (var param in _queryParams)
                    {
                        query.Append($"{Uri.EscapeDataString(param.Key)}={Uri.EscapeDataString(param.Value)}&");
                    }
                    var newUriString = $"{baseUri.AbsoluteUri}?{query.ToString().TrimEnd('&')}";
                    _request.RequestUri = new Uri(newUriString);
                }

                // 处理请求体
                if (_bodyData != null)
                {
                    var json = JsonConvert.SerializeObject(_bodyData);
                    _request.Content = new StringContent(json, Encoding.UTF8, "application/json");
                }
                else if (!string.IsNullOrEmpty(_customBody))
                {
                    _request.Content = new StringContent(_customBody, Encoding.UTF8, _contentType);
                }
            }

            private void ApplyDefaultHeaders()
            {
                foreach (var header in Instance.DefaultHeaders)
                {
                    _request.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }

            private async Task<Response> ProcessResponse(HttpResponseMessage response)
            {
                var content = await response.Content.ReadAsStringAsync();

                return new Response
                {
                    StatusCode = response.StatusCode,
                    IsSuccess = response.IsSuccessStatusCode,
                    Content = content,
                    Headers = response.Headers
                };
            }
        }
        #endregion

        #region Response Model
        public class Response
        {
            public bool IsSuccess { get; set; }
            public HttpStatusCode StatusCode { get; set; }
            public string Content { get; set; }
            public string ErrorMessage { get; set; }
            public HttpResponseHeaders Headers { get; set; }

            public T GetData<T>()
            {
                return JsonConvert.DeserializeObject<T>(Content);
            }

            public string GetJson()
            {
                return Content;
            }
        }
        #endregion
    }


// 示例使用：
/** 
// 初始化配置（通常放在程序启动时）
HttpClientService.Instance
    .SetBaseUrl("https://api.example.com/v1/")
    .SetTimeout(TimeSpan.FromSeconds(45))
    .DefaultHeaders.Add("Authorization", "Bearer YOUR_TOKEN");

// 发送GET请求
var getResponse = await HttpClientService.Instance
    .Get("users")
    .AddQueryParam("page", "1")
    .AddHeader("Cache-Control", "no-cache")
    .SendAsync();

if (getResponse.IsSuccess)
{
    var users = getResponse.GetData<List<User>>();
}

// 发送POST请求
var newUser = new { name = "John", age = 30 };
var postResponse = await HttpClientService.Instance
    .Post("users")
    .SetBody(newUser)
    .SendAsync();

if (!postResponse.IsSuccess)
{
    Debug.LogError($"Error: {postResponse.ErrorMessage}");
}

*/
